<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #imageBox{
            position: relative;
        }
        #cutBox{
            position: absolute;
            top: 0;
            left: 0;
            width: 160px;
            height: 160px;
            border: 1px solid blue;
        }
    </style>
</head>
<body>
<h1>头像上传</h1>
<input type="file" id="img">
<div id="imageBox">
    <canvas id="myCanvas" width="500" height="500" style="border: 1px solid red"></canvas>
    <div id="cutBox"></div>
</div>
<button id="shangchuan">上传</button>
<div>
    <h2>预览</h2>
    <canvas id="newCanvas" width="200" height="200" style="border: 1px solid blue"></canvas>
</div>
<h2>头像</h2>
<img id="touxiang" alt="">


<script src="js/jquery-1.11.3.js"></script>
<script>
    let hb=$('#myCanvas')[0].getContext('2d')
    let newhb=$('#newCanvas')[0].getContext('2d')

    //预览选中的图片
    $('#img').change(function () {
        let imgFile=this.files[0]
        let reader=new FileReader()
        reader.readAsDataURL(imgFile)
        reader.onload=function () {
            let img=document.createElement('img')
            img.src=this.result
            img.onload=function () {
                hb.drawImage(img,0,0,500,500)
            }
        }
    })
    // 拖动cutBox
    $('#cutBox').mousedown(function (e) {
        let downEvent=e
        let divLeft=parseInt($(this).css('left'))
        let divTop=parseInt($(this).css('top'))
        $(this).mousemove(function (e) {
            let moveEvent=e
            $(this).css({
                left:moveEvent.clientX-downEvent.clientX+divLeft,
                top:moveEvent.clientY-downEvent.clientY+divTop
            })
        })
    })
    $('#cutBox').mouseup(function () {
        $('#cutBox').off('mousemove')
        let x=parseInt($(this).css('left'))
        let y=parseInt($(this).css('top'))
        let imgData=hb.getImageData(x,y,200,200)
        newhb.putImageData(imgData,0,0)
    })

    $('#shangchuan').click(function () {
        let imgUrl=$('#newCanvas')[0].toDataURL()

        $.ajax({
            url:'/scTouXiang',
            method:'post',
            data:{imgUrl},
            success(data){
                console.log(data.data)
                $('#touxiang')[0].src=data.data
            }
        })
    })
</script>
</body>
</html>